from django.shortcuts import render

# Create your views here.
from rest_framework import permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin
from rest_framework_simplejwt.authentication import JWTAuthentication

from app.user_operate.authentication import IsOwnerOrReadOnly
from app.user_operate.models import UserFav, UserLeavingMessage, UserAddress
from app.user_operate.serializers import UserFavSerializer, UserFavDetailSerializer, LeaveMessageSearializer, \
    UserAddressSerializer


class UserFavView(GenericViewSet, ListModelMixin, CreateModelMixin, DestroyModelMixin):
    serializer_class = UserFavSerializer
    # 可以根据商品的id来进行删除
    lookup_field = 'goods_id'
    # 局部认证管理
    authentication_classes = [JWTAuthentication, SessionAuthentication]

    # 权限管理
    # 添加自定义的权限类
    permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]

    def get_queryset(self):
        return UserFav.objects.filter(user=self.request.user)

    # 动态序列化
    def get_serializer_class(self):
        if self.action == 'list':
            return UserFavDetailSerializer
        else:
            return UserFavSerializer


class LeaveMessageView(GenericViewSet, CreateModelMixin, ListModelMixin, DestroyModelMixin, RetrieveModelMixin):
    serializer_class = LeaveMessageSearializer
    authentication_classes = [JWTAuthentication, SessionAuthentication]
    permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]

    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)


class UserAddressView(ModelViewSet):
    serializer_class = UserAddressSerializer
    authentication_classes = [JWTAuthentication, SessionAuthentication]
    permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)
